﻿using System;
using System.Timers;

namespace Com.Lancetinc.Evs.Helpers
{
    public class DelegateDisposable : IDisposable
    {
        private readonly Action _dispose;

        public DelegateDisposable(Action dispose)
        {
            _dispose = dispose;
        }

        private bool _disposed = false;
        public void Dispose()
        {
            if (_disposed)
                return;
            _disposed = true;
            _dispose();
        }
    }

    /// <summary>
    /// 超时之后自动调用Dispose
    /// </summary>
    public class TimeoutDelegateDisposable : IDisposable
    {
        private readonly Action _disposeAction;
        private bool _disposed = false;
        private readonly Timer _timer;

        public TimeoutDelegateDisposable(Action dispose, TimeSpan timeout)
        {
            _disposeAction = dispose;
            _timer = new Timer { Interval = timeout.TotalMilliseconds, AutoReset = false };
            _timer.Elapsed += (s, e) =>
            {
                Dispose();
            };

            _timer.Start();
        }

        public void Dispose()
        {
            if (_disposed)
                return;

            _timer?.Stop();

            _disposeAction();
        }
    }
}
